#include "eventanalyzer.h"
#include <QThread>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QString>
#include <QPair>
#include "eci.h"
#include "coordtopocentric.h"
#include "util.h"

void EventAnalyzer::parseCsvEvents(const QString& csvPath) {
    QFile file(csvPath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开事件文件:" << csvPath;
        return;
    }

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        QStringList parts = line.split(',');

        // 格式应为：中心频率,开始时间,结束时间
        if (parts.size() != 3) {
            qWarning() << "无效的CSV行，应有3列:" << line;
            continue;
        }

        EventData event;
        bool ok;
        event.centerFreq = parts[0].toInt(&ok);
        if (!ok) {
            qWarning() << "无效的中心频率:" << parts[0];
            continue;
        }

        // 解析时间（保持UTC）
        event.start = QDateTime::fromString(parts[1], "yyyyMMdd-HHmmss");
        event.start.setTimeSpec(Qt::UTC);
        event.end = QDateTime::fromString(parts[2], "yyyyMMdd-HHmmss");
        event.end.setTimeSpec(Qt::UTC);

        if (!event.start.isValid() || !event.end.isValid()) {
            qWarning() << "时间格式错误:" << parts[1] << "或" << parts[2];
            continue;
        }

        m_events.append(event);
        qDebug() << "解析事件: 频率" << event.centerFreq << "MHz, 时间窗口"
                 << event.start.toString("yyyy-MM-dd hh:mm:ss") << "-"
                 << event.end.toString("hh:mm:ss");
    }

}
void EventAnalyzer::setAnalysisParams(QDateTime start, QDateTime end,
                                      QString noradPath, QString tlePath,QString eventsPath,
                                      SatellitePos::TleSource tleSource,
                                      bool selectAll)
{
    // 参数有效性验证
    if (noradPath.isEmpty() && !selectAll) {
        qCritical() << "NORAD路径未设置且未启用全选模式!";
        emit analysisFinished(false);
        return;
    }
    // // 时间参数
    // m_startTime = start.isValid() ? start : QDateTime::currentDateTime();
    // m_endTime = end.isValid() ? end : m_startTime.addSecs(60*60);//，在mainwindow中配置了，在此处修改将不会影响

    // 路径参数
    m_noradPath = QDir(noradPath).exists() ? noradPath : "";
    m_tlePath = QDir(tlePath).exists() ? tlePath : "";

    // 模式参数
    m_tleSource = tleSource;
    m_selectAllNorad = selectAll;

    qDebug() << "分析参数设置:";
    qDebug() << "- NORAD路径:" << m_noradPath;
    qDebug() << "- TLE路径:" << m_tlePath;

}

void EventAnalyzer::startAnalysis() {
    auto loc = m_observer.GetLocation();
    // 将弧度转回度数，供debug观察
    qDebug() << "程序实际接收地面站坐标:"
             << "纬度: " << libsgp4::Util::RadiansToDegrees(loc.latitude) << "°\n"
             << "经度: " << libsgp4::Util::RadiansToDegrees(loc.longitude) << "°\n"
             << "高度: " << loc.altitude << " km\n";

    // 加载数据
    m_satPos.loadData(m_noradPath, m_tlePath, m_tleSource, m_selectAllNorad);
    parseCsvEvents(m_eventsPath);


    // 遍历所有事件（每个事件对应一个中心频率）
    foreach (const EventData &event, m_events) {
        int centerFreq = event.centerFreq;
        const QSet<int>& noradIds = m_satPos.getNoradIdsByFrequency(centerFreq);

        if (noradIds.isEmpty()) {
            qWarning() << "! 频率" << centerFreq << "MHz 未找到关联的卫星!";
            continue;
        }

        qDebug() << "\n==== 开始分析频率:" << centerFreq << "MHz ===="
                 << "关联卫星数量:" << noradIds.size()
                 << "照射事件时间窗口:" << event.start.toString("yyyy-MM-dd hh:mm:ss")
                 << "-" << event.end.toString("hh:mm:ss");

        foreach (int noradId, noradIds) {
            detectSatelliteEvents(centerFreq, noradId, event.start, event.end);
        }
    }

    saveToCSV(m_allEvents);
    emit analysisFinished(!m_allEvents.isEmpty());
}

// 核心检测逻辑
void EventAnalyzer::detectSatelliteEvents(int centerFreq, int noradId,
                                         const QDateTime& start, const QDateTime& end) {
    QPair<int, int> freqSatKey(centerFreq, noradId);
    // 获取当前频率关联的NORAD ID集合
    const QSet<int>& noradIds = m_satPos.getNoradIdsByFrequency(centerFreq);
    int totalSteps = start.secsTo(end) / m_timeStepSec;
    bool hasEvent = false;

    qDebug() << "\n-- 检测卫星:" << noradId
             << " 步长:" << m_timeStepSec << "秒"
             << " 总步数:" << totalSteps;

    for (int i = 0; i <= totalSteps; ++i) {
        // QDateTime current = start.addSecs(i * m_timeStepSec);
        QDateTime current = start.addSecs(i * m_timeStepSec);

        try {
            // 计算卫星位置
            auto positions = m_satPos.calculatePositions(current, noradIds);
            auto it = positions.find(noradId); // 使用 find 代替 contains+operator[]
            if (it == positions.end()) {
                // qDebug() << "[" << current.toString("hh:mm:ss") << "] 卫星未找到";
                continue;
            }

            // 计算仰角
            const libsgp4::Eci& eci = it.value();
            auto topo = m_observer.GetLookAngle(eci);
            double elev = libsgp4::Util::RadiansToDegrees(topo.elevation);
            qDebug() << "计算仰角:" << elev; // 确保此处输出合理值

            // 状态跟踪
            if (elev >= m_minElevation) {
                if (!m_satelliteState.value(freqSatKey, false)) {
                    // 事件开始
                    SatelliteEvent newEvent;
                    newEvent.centerFreq = centerFreq;
                    newEvent.noradId = noradId;
                    newEvent.startTime = current;
                    newEvent.maxElevation = elev;
                    m_allEvents[centerFreq].append(newEvent);
                    m_satelliteState[freqSatKey] = true;
                    qDebug() << "[" << current.toString("hh:mm:ss") << "] 事件开始 仰角:" << elev << "°";
                    qDebug() << "事件开始: 频率" << centerFreq << "卫星" << noradId;
                    hasEvent = true;
                } else {
                    // 更新最大仰角
                    SatelliteEvent& lastEvent = m_allEvents[centerFreq].last();
                    if (elev > lastEvent.maxElevation) {
                        lastEvent.maxElevation = elev;
                        qDebug() << "[" << current.toString("hh:mm:ss") << "] 更新仰角至:" << elev << "°";
                    }
                    // auto& lastEvent = m_allEvents[centerFreq].last();
                    // lastEvent.maxElevation = qMax(lastEvent.maxElevation, elev);
                }
            } else {
                if (m_satelliteState.value(freqSatKey, false)) {
                    // 事件结束
                    SatelliteEvent& lastEvent = m_allEvents[centerFreq].last();
                    lastEvent.endTime = current;
                    m_satelliteState[freqSatKey] = false;
                    qDebug() << "[" << current.toString("hh:mm:ss") << "] 事件结束";
                }
            }
        } catch (const std::exception& e) {
            qWarning() << "卫星" << noradId << "计算错误:" << e.what();
        }

        emit progressUpdated((i * 100) / totalSteps);
    }

    // 强制结束未关闭事件
    if (m_satelliteState.value(freqSatKey, false)) {
        SatelliteEvent& lastEvent = m_allEvents[centerFreq].last();
        lastEvent.endTime = end;
        m_satelliteState[freqSatKey] = false;
        qDebug() << "[强制结束] 频率:" << centerFreq << "MHz 卫星:" << noradId;
    }

    if (!hasEvent) {
        qDebug() << "未检测到有效事件";
    }
}


void EventAnalyzer::saveToCSV(const QMap<int, QList<SatelliteEvent>>& events) {
    //  确保输出目录存在
    QDir dir(m_outputDir);
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            qCritical() << "无法创建输出目录:" << m_outputDir;
            return;
        }
    }
    // 添加文件权限检查
    QFileInfo info(dir.absolutePath());
    if (!info.isWritable()) {
        qCritical() << "目录无写入权限:" << m_outputDir;
        return;
    }

    QFile file(m_outputDir + "/匹配结果.csv");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        // 添加BOM头（强制UTF-8标识）
        file.write("\uFEFF");
        QTextStream stream(&file);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
        stream.setCodec("UTF-8"); // Qt5兼容方案
#else
            // Qt6需通过QStringConverter设置编码,并且需要#include <QStringConverter>
        #include <QStringConverter>
        stream.setEncoding(QStringConverter::Utf8);
#endif
        //表头设置
        // stream << "中心频率_MHz,NORAD ID,开始时间UTC,结束时间UTC,持续时间_秒,最大仰角_度\n";
         stream << "Freq_MHz,NORAD ID,Start(UTC),End(UTC),Duration(sec),Max_elev(deg)\n";

        QList<int> frequencies = events.keys();
        foreach (int freq, frequencies) {
            foreach (const SatelliteEvent &event, events[freq]) {
                int duration = event.startTime.secsTo(event.endTime);
                stream << event.centerFreq << ","
                       << event.noradId << ","
                       << event.startTime.toString("yyyy-MM-dd hh:mm:ss") << ","
                       << event.endTime.toString("yyyy-MM-dd hh:mm:ss") << ","
                       << duration << ","
                       << QString::number(event.maxElevation, 'f', 2) << "\n";
            }
        }

        qDebug() << "结果已保存至:" << file.fileName();
}
}
